import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const [reqContext, resContext] = context.getArgs();

    const start = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => {
          const end = Date.now();
          console.log(` =====================================================================================================
            Request: [${reqContext.method} ${ reqContext.url} ${reqContext.headers['x-real-ip'] || reqContext.headers['x-forwarded-for'] || reqContext.ip}]
            Response: [${resContext.statusCode} ${JSON.stringify(resContext._headers)}]
            Spend time: [${end - start}ms]
=====================================================================================================`
          )
        }),
      );
  }
}